package com.nl.math;

import java.util.Arrays;

public class PrintNBitMaxNum {

	public void printNMaxNum(int n){
		char[] number = new char[n];
		Arrays.fill(number, '0');
		while(increment(number)){
			print(number);
		}
	}

	private void print(char[] number) {
		//记录是否是以零开始的
		boolean isBeginning0 = true;
		int len = number.length;
		for(int i=0;i<len;i++){
			if(isBeginning0&&number[i]!='0'){
				isBeginning0  = false;
			}

			if(!isBeginning0){
				System.out.print(String.format("%c",number[i]));
			}
		}
		System.out.println();
	}

	private boolean increment(char[] number) {
		boolean isOverflow = false;
		int nTakeOver = 0;
		int len = number.length;
		for(int i=len-1;i>=0;i--){
			//执行进位
			int nSum = number[i] -'0' +nTakeOver;
			//自增
			if(i == len - 1){
				nSum++;
			}
			//是否需要进位
			if(nSum >= 10){
				//高位的话，溢出,说明已经到最大值
				if(i==0){
					isOverflow = true;
				}else{
					//低位计算进位值
					nSum-=10;
					nTakeOver =1;
					number[i] =(char) ('0' +nSum);
				}
			}else{
				//不需要进位,就停止了
				number[i] =(char) ('0' +nSum);
				break;
			}
		}
		return !isOverflow;
	}
	
	//全排列实现方式
	void print1ToMaxOfNdigits(int n){
		if(n<=0)
			return ;
		char[] number = new char[n];
		//第一位从０－９
		for(int i=0;i<10;i++){
			number[0] =(char) (i+'0');
			print1ToMaxOfNDigitsRecursively(number,0);
		}
	}

	private void print1ToMaxOfNDigitsRecursively(char[] number, int index) {
		
		if(index == number.length-1 ){
			print(number);
			return;
		}
		
		//剩余的位数也是从零到９
		for(int i=0;i<10;i++){
			number[index+1] =(char) (i+'0');
			print1ToMaxOfNDigitsRecursively(number,index+1);
		}
		
	}

}
